import React, { useEffect, useState } from "react";
import { Space, Table, Button, message, Input, Modal, Form } from "antd";

import type { TableProps } from "antd";
import http from "../../utils/http";
// 类型
interface DataType {
  key: React.Key;
  restorativesid: string;
  restorativesimage: string;
  restorativestitle: string;
  restorativesstate: string;
  restorativesdesc: string;
}

const Index: React.FC = () => {
  // 数据
   const [originalDatalist, setOriginalDatalist] = useState<DataType[]>([]);
  const [datalist, setDatalist] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState(""); // 编辑
  const columns: TableProps<DataType>["columns"] = [
    {
      title: (
        <div>
          <Button
            disabled={selectedRowKeys.length === 0}
            type="primary"
            style={{ marginRight: "10px" }}
          >
            批量删除
          </Button>
          ID
        </div>
      ),
      align: "center",
      dataIndex: "restorativesid",
      key: "restorativesid",
    },
    {
      title: "图片",
      align: "center",
      dataIndex: "restorativesimage",
      key: "restorativesimage",
      render: (text, record) => {
        return (
          <img
            src={text}
            alt={record.restorativesimage}
            style={{ width: "80px", height: "80px" }}
          />
        );
      },
    },
    {
      title: "类型",
      align: "center",
      dataIndex: "restorativesstate",
      key: "restorativesstate",
    },
    {
      title: "名称",
      align: "center",
      dataIndex: "restorativesname",
      key: "restorativesname",
    },
    {
      title: "价格",
      align: "center",
      dataIndex: "restorativesprice",
      key: "restorativesprice",
    },
    {
      title: "Action",
      align: "center",
      key: "restorativesid",
      render: (record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => EditshowModal(record)}>
            编辑
          </Button>
          <Button type="primary" danger onClick={() => hanDel(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 分页
  const [pageCode, setPageCode] = useState(1);
  const [pageSize, setPageSize] = useState(200);
  // 渲染数据
  const FearchList = async () => {
    const res = await http.get("/restorative/list", {
      params: {
        pageCode,
        pageSize,
      },
    });
    const { code, data } = res.data;
    console.log(data);
    
    if (code === 200) {
      setDatalist(data);
      setOriginalDatalist(data);
    }
  };
  useEffect(() => {
    FearchList();
  }, []);
  // 删除数据
  const hanDel = async (record: DataType) => {
    const res = await http.delete("/restorative/list", {
      params: {
        id: record.restorativesid,
      },
    });
    const { code } = res.data;
    if (code === 20000) {
      message.success("删除成功");
      FearchList();
    }
  };
  // 添加数据
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [DialogState, setDialogState] = useState(true);
  // 编辑/添加
  const AddshowModal = () => {
    form.resetFields();
    setIsModalOpen(true);
    setDialogState(true);
  };
  const EditshowModal = (record: DataType) => {
    form.setFieldsValue(record);
    setIsModalOpen(true);
    setDialogState(false);
  };
  const handleOk = async () => {
    if (DialogState) {
      try {
        const formData = form.getFieldsValue();
       console.log(formData);
       

        // 发送put请求添加数据
        const res = await http.put("/restorative/list", {
          id: formData.restorativesid,
          name: formData.restorativesname,
          price: formData.restorativesprice,
          state: formData.restorativesstate,
          title: formData.restorativestitle,
          desc: formData.restorativesdesc,
          image: formData.restorativesimage,
          count: formData.restorativescount,
          inven: formData.restorativesinven,
        });
        const { code } = res.data;
        if (code === 20000) {
          message.success("添加成功");
          FearchList();
          setIsModalOpen(false);
        }
      } catch (error) {
        console.error("添加数据出错:", error);
        message.error("添加数据失败");
      }
    } else {
      // 编辑逻辑
        try {
        const formData = form.getFieldsValue();
        // 发送put请求添加数据
        const res = await http.post("/restorative/list", {
          name: formData.restorativesname,
          price: formData.restorativesprice,
          state: formData.restorativesstate,
          title: formData.restorativestitle,
          desc: formData.restorativesdesc,
          image: formData.restorativesimage,
          count: formData.restorativescount,
          inven: formData.restorativesinven,
          id: formData.restorativesid,
        });
        const { code } = res.data;
        if (code === 20000) {
          message.success("添加成功");
          FearchList();
          setIsModalOpen(false);
        }
      } catch (error) {
        console.error("添加数据出错:", error);
        message.error("添加数据失败");
      }
    }
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //搜索
  
   const { Search } = Input;
 const onSearch = (value: string) => {
    setSearchValue(value);
    if (!value) {
      setDatalist(originalDatalist);
    } else {
      const filteredData = originalDatalist.filter((item) =>
        Object.values(item).some((v) =>
          String(v).toLowerCase().includes(value.toLowerCase())
        )
      );
      setDatalist(filteredData);
    }
  };
  return (
    <div>
      <Button
        type="primary"
        style={{ marginRight: "60px" }}
        onClick={() => AddshowModal()}
      >
        增加数据
      </Button>
      <Search
          placeholder="请输入搜索内容"
          allowClear
          enterButton="搜索"
          size="small"
          style={{ width: "300px" }}
          onSearch={onSearch}
        />
      <Table<DataType>
        rowKey={"restorativesid"}
        rowSelection={{
          onChange(newSelectedRowKeys: React.Key[]) {
            console.log(newSelectedRowKeys);
            setSelectedRowKeys(newSelectedRowKeys);
          },
        }}
        columns={columns}
        dataSource={datalist}
      />

      {/* 添加编辑和增加弹框 */}
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} name="control-hooks" style={{ maxWidth: 600 }}>
          <Form.Item name="restorativesid" label="ID" rules={[{ required: true }]}>
            <Input  disabled={!DialogState} />
          </Form.Item>

          <Form.Item
            name="restorativesname"
            label="药品名称"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="restorativesprice"
            label="药品价格"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="restorativesimage"
            label="药品图片"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="restorativesstate"
            label="药品分类"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>


          <Form.Item
            name="restorativescount"
            label="库存"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="restorativesinven"
            label="销量"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="restorativestitle"
            label="药品规格"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="restorativesdesc"
            label="药品描述"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          
        </Form>
      </Modal>
    </div>
  );
};

export default Index;
